import Axios from 'axios'

Axios.defaults.baseURL = 'http://139.199.33.51:9091/'
// 授权
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/json';
Axios.defaults.timeout = 50000

Axios.interceptors.request.use(
    config => {
        config.headers.common["Content-Type"] = "application/json"
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

Axios.interceptors.response.use(
    response => {
        if (response.data.code != 200) {
            return Promise.reject(response.data)
        }
        return Promise.resolve(response.data)
    },
    error => {
        return Promise.reject(error)
    }
)

function getFunc(url, params = {}, pageable = false, headers = {}) {
    // 处理分页参数问题
    if (pageable) {
        if (params.pageNo) {
            params.page = params.pageNo - 1
            delete params.pageNo
        }
        if (params.pageSize) {
            params.size = params.pageSize
            delete params.pageSize
        }
        if (params.sortColumns) {
            const sortArr = params.sortColumns.split(' ')
            params.sort = sortArr[0] + ',' + sortArr[1]
            delete params.sortColumns
        } else {
            delete params.sortColumns
        }
    }
    return new Promise(((resolve, reject) => {
        Axios.get(url, {
            params: params,
            headers: headers
        }).then(response => {
            resolve(response.data)
        }).catch(err => {
            reject(err)
        })
    }))
}

function postFunc(url, data = {}) {
    return new Promise(((resolve, reject) => {
        Axios.post(url, data)
            .then(response => {
                resolve(response.data)
            }), err => {
                reject(err)
            }
    }))
}

function putFunc(url, data = {}) {
    return new Promise(((resolve, reject) => {
        Axios.put(url, data)
            .then(response => {
                resolve(response.data)
            }), err => {
                reject(err)
            }
    }))
}

function deleteFunc(url, params = {}) {
    return new Promise(((resolve, reject) => {
        Axios.delete(url, {
            params: params
        }).then(response => {
            resolve(response.data)
        }).catch(err => {
            reject(err)
        })
    }))
}

export {
    getFunc,
    postFunc,
    putFunc,
    deleteFunc
}
